
import global_config
import keras
import util.img_utils as img_utils

model = None

def predict_one_letter(im):
    """
    预测信息
    :param im: 预测的图片
    :return: 预测值
    """
    global model
    if model is None:
        init_model()

    width, height = global_config.my_config.img_size
    i = img_utils.format_img_to_model(im, global_config.my_config.img_size).reshape((1, width, height, -1))

    # 预测
    result = model.predict_classes(i)
    result = result.reshape((-1,))
    # 取第一个数
    result = result[0]
    result = global_config.my_config.char_set[result]
    # print("预测结果为：{}".format(result))
    return result

def predict_img(im):
    all_img = global_config.preprocess_img.cut_img(im)
    if len(all_img) == 0:
        print("切割失败")
        raise BaseException("预测失败，图片切割失败")

    value = ''
    try:
        for i in all_img:
            # 预测
            predict_text = predict_one_letter(i)
            value = value + predict_text
    except BaseException as b:
        print("预测异常:{}".format(b))
        raise BaseException("预测失败，参数错误")
    return value

def init_model():
    '''
    初始化模型
    :return:
    '''
    global model

    # 重新创建完全相同的模型，包括其权重和优化程序
    model = keras.models.load_model(global_config.model_save_path)
    # 显示网络结构
    model.summary()
    print("加载{}模型完成".format(global_config.model_save_path))
    # model_predict(getTestJsonData())
    # print("测试预测完成")